import { defineStore } from "pinia"
import { ref, computed } from "vue"
import { getCartList, addCartList, deleteCartList } from "@/api/cart"
import { useUserStore } from "./user"

export const useCartStore = defineStore("cart", () => {
    const userStore = useUserStore()
    let isLogin = computed(() => userStore.userInfo.token)
    /**
     * 定义state
     */
    const cartList = ref([])

    /**
     * 定义action
     */
    // 获取购物车列表
    const getCart = () => {
        getCartList().then(res => {
            cartList.value = res.result
        })
    }
    // 添加购物车
    const addCart = async (goods) => {
        const { skuId, count } = goods
        // 判断是否登录
        if (isLogin.value) {
            await addCartList({ skuId, count })
            getCart()
        } else {
            // 判断是否已经添加到购物车
            const good = cartList.value.find(item => item.skuId === goods.skuId)
            if (good) {
                good.count += goods.count
            } else {
                cartList.value.push(goods)
            }
        }

    }
    // 删除购物车商品
    const deleteCart = async (skuId) => {
        if (isLogin.value) {
            await deleteCartList([skuId])
            getCart()
        } else {
            cartList.value = cartList.value.filter(item => item.skuId !== skuId)
        }
    }

    // 清除购物车
    const clearCartList = () => {
        cartList.value = []
    }

    // 单选
    const singleCheck = (skuId, selected) => {
        cartList.value.find(item => item.skuId === skuId).selected = selected
    }
    // 全选or取消全选
    const allCheck = (value) => {
        cartList.value.forEach(item => item.selected = value)
    }

    /**
     * 定义getters
     */
    // 总数量和总价格
    let allCount = computed(() => cartList.value.reduce((totalCount, item) => totalCount + item.count, 0))
    let allPrice = computed(() => cartList.value.reduce((totalPrice, item) => totalPrice + item.count * item.price, 0))

    // 是否全选
    let isAll = computed(() => {
        if (cartList.value.length === 0) return false
        return cartList.value.every(item => item.selected)
    })

    // 选中的数量和价格
    let selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((totalCount, value) => totalCount + value.count, 0))
    let selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((totalPrice, value) => totalPrice + value.count * value.price, 0))

    return {
        cartList,
        allCount,
        allPrice,
        isAll,
        selectedCount,
        selectedPrice,
        addCart,
        deleteCart,
        allCheck,
        singleCheck,
        clearCartList,
        getCart
    }
}, { persist: true })
